package com.vipboot.auth.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.ObjectUtil;
import com.vipboot.auth.domain.form.LoginBody;
import com.vipboot.auth.domain.vo.AuthTokenVo;
import com.vipboot.auth.service.AuthService;
import com.vipboot.auth.strategy.AuthStrategy;
import com.vipboot.framework.biz.api.auth.ApiClientService;
import com.vipboot.framework.biz.api.auth.domain.vo.ApiClientVo;
import com.vipboot.framework.core.constant.Const;
import com.vipboot.framework.core.domain.R;
import com.vipboot.framework.core.util.StringUtil;
import com.vipboot.framework.core.util.ValidatorBeanUtil;
import com.vipboot.framework.jackson.util.JsonUtil;
import com.vipboot.framework.satoken.helper.LoginHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Auth认证
 */
@Slf4j
@SaIgnore
@RequiredArgsConstructor
@RestController
@RequestMapping("/auth")
public class AuthController {

    private final ApiClientService apiClientService;
    private final AuthService authService;

    /**
     * 登录
     *
     * @param jsonBody jsonBody(可动态转换密码登录Body,短信登录Body,小程序Body)
     */
    @PostMapping("/login")
    public R<AuthTokenVo> login(@RequestBody String jsonBody) {
        LoginBody loginBody = JsonUtil.parseObject(jsonBody, LoginBody.class);
        ValidatorBeanUtil.validate(loginBody);
        // 客户端ID 和 授权类型（密码登录、小程序登录 等）
        String clientId = loginBody.getClientId();
        String grantType = loginBody.getGrantType();
        ApiClientVo clientVo = apiClientService.getByClientId(clientId);

        // 查询不到 client 或 client 内不包含 grantType
        if (ObjectUtil.isNull(clientVo) || !StringUtil.contains(clientVo.getGrantType(), grantType)) {
            log.info("客户端Id: {} 认证类型 GrantType ：{} 异常!.", clientId, grantType);
            return R.fail("客户端ID或授权类型错误");
        }
        if (Const.StatusDisable.equals(clientVo.getStatus())) {
            return R.fail("认证权限类型已禁用");
        }
        // 校验租户
//        loginService.checkTenant(loginBody.getTenantId());

        AuthTokenVo loginVo = AuthStrategy.login(jsonBody, clientVo, grantType);
        authService.afterLogin();

        Long userId = LoginHelper.getUserId();
//        scheduledExecutorService.schedule(() -> {
//            SseMessageDto dto = new SseMessageDto();
//            dto.setMessage("欢迎登录RuoYi-Vue-Plus后台管理系统");
//            dto.setUserIds(List.of(userId));
//            SseMessageUtils.publishMessage(dto);
//        }, 5, TimeUnit.SECONDS);

        return R.ok(loginVo);
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public R<Void> logout() {
        authService.logout();
        return R.ok();
    }

}
